package otimista.threads;

import java.util.Random;

import util.Storage;
import util.Table;

public class Modifier implements Runnable {

	private final Table table;
	private final int iterations;

	public Modifier(Table table, int iterations) {
		this.table = table;
		this.iterations = iterations;
	}

	@Override
	public void run() {
		try {
			modifySomeValues();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void modifySomeValues() throws InterruptedException {
		int temp = 0;
		while (temp < this.iterations) {
			if(modifyValue()){
				temp++;
			}
		}
	}

	public boolean modifyValue() {
		Random random = new Random();
		int randomKey = random.nextInt(table.size());
		Storage<String> value = table.readValue(randomKey);
		
		if(value == null){
			return false;
		}
		
		try{
			value.getWriteLock().lock();
			value.setValue(String.valueOf(Integer.parseInt(value.getValue()) + 1));
			
		} finally {
			value.getWriteLock().unlock();
		}
		
		return true;
	}
	
}
